package com.iotechn.unimall.app.api.enterprise;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dobbinsoft.fw.core.Const;
import com.dobbinsoft.fw.core.exception.AppServiceException;
import com.dobbinsoft.fw.core.exception.ServiceException;
import com.dobbinsoft.fw.core.util.SessionUtil;
import com.iotechn.unimall.data.domain.EnterpriseDO;
import com.iotechn.unimall.data.domain.UserDO;
import com.iotechn.unimall.data.dto.AdminDTO;
import com.iotechn.unimall.data.dto.UserDTO;
import com.iotechn.unimall.data.exception.ExceptionDefinition;
import com.iotechn.unimall.data.mapper.EnterpriseMapper;
import com.iotechn.unimall.data.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

@Service("appEnterpriseService")
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, EnterpriseDO> implements EnterpriseService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private SessionUtil<UserDTO, AdminDTO> sessionUtil;

    @Autowired
    private StringRedisTemplate userRedisTemplate;

    @Override
    public EnterpriseDO detail(Long userId) throws ServiceException {
        QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserDO::getId, userId);
        UserDO userDO = userMapper.selectOne(wrapper);

        QueryWrapper<EnterpriseDO> enterpriseDOQueryWrapper = new QueryWrapper<>();
        enterpriseDOQueryWrapper.lambda().eq(EnterpriseDO::getId, userDO.getEnterpriseId());
        return baseMapper.selectOne(enterpriseDOQueryWrapper);
    }

    @Override
    public String unbind(Long userId, String accessToken) throws ServiceException {
        QueryWrapper<UserDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserDO::getId, userId);
        UserDO userDO = userMapper.selectOne(wrapper);
        userDO.setEnterpriseId(-1L);

        if (userMapper.updateById(userDO) <= 0) {
            throw new AppServiceException(ExceptionDefinition.APP_UNKNOWN_EXCEPTION);
        } else {
            //更新SESSION缓存
            UserDTO user = sessionUtil.getUser();
            user.setEnterpriseId(-1L);
            userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(user));
        }
        return "ok";
    }

    @Override
    public EnterpriseDO eDetail(Long enterpriseId, Long userId) throws ServiceException {
        QueryWrapper<EnterpriseDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(EnterpriseDO::getId, enterpriseId);
        return baseMapper.selectOne(wrapper);
    }
}
